package com.easy.sys.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.bean.SysRole;
import com.easy.common.bean.SysUser;
import com.easy.common.enumbean.UserStatus;
import com.easy.common.service.IUserService;
import com.easy.sys.mapper.SysUserMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@DubboService
public class SysUserService extends ServiceImpl<SysUserMapper,SysUser> implements IUserService {

    @Autowired
    SysUserMapper userMapper;
    @Override
    public SysUser insert(SysUser user) {
        userMapper.insert(user);
        SysUser result=this.getByID(user.getId());
        return result;
    }

    @Override
    public SysUser update(SysUser user) {
        userMapper.updateById(user);
        SysUser result=this.getByID(user.getId());
        return result;
    }

    @Override
    public int delete(Integer id) {
        super.removeById(id);
        return 1;
    }

    @Override
    public SysUser getByID(Integer id) {
        return super.getById(id);
    }

    @Override
    public IPage<SysUser> getListByPage(IPage page, SysUser user) {

//        Wrapper wrapper=new QueryWrapper(user);
//        IPage result=userMapper.selectPage(page,wrapper);
//        return result;
        QueryWrapper<SysUser> wrapper=new QueryWrapper(user);
        return super.page(page,wrapper);
    }

    @Override
    public List<SysUser> getList(SysUser user) {
        Wrapper wrapper=new QueryWrapper(user);
//        List<SysUser> result=userMapper.selectList(wrapper);
//        return result;
        return super.list(wrapper);
    }

    @Override
    public int setStatus(Integer id){
        SysUser user=super.getById(id);
        UserStatus status=user.getStatus();
        if(status==UserStatus.DISABLE){
            user.setStatus(UserStatus.NORMAL);
        }else{
            user.setStatus(UserStatus.DISABLE);
        }
        super.updateById(user);
        return 1;
    }

    @Override
    public SysUser assignRole(SysUser user) {
        //先清空该用户原有的角色信息
        super.getBaseMapper().deleteUserRoleByUserID(user.getId());
        //在添加
        List<SysRole> roles=user.getRoles();
        for(SysRole role:roles){
            super.getBaseMapper().insertUserRole(user.getId(),role.getId());
        }
        return super.getById(user.getId());
    }

    @Override
    public SysUser getByUsername(String username){

        return super.getBaseMapper().getByUsername(username);
    }
}
